﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using shelltwitlib;

namespace twit
{
	class Program
	{
		static void Main(string[] args)
		{
			try
			{
				//Debug.Assert(false, "Attach VS here!");

				if (args.Length == 0)
				{
					ShowUsage();
					return;
				}

				if (args[0].ToLower() == "/c")
				{
					TwitterUser.ClearCredentials();
					Console.WriteLine("User credentials cleared!");
					return;
				}

				string status = BitLyHelper.Util.GetShortenString(args);
				string response = shelltwitlib.Status.Update.UpdateStatus(status);

				if (response != "OK")
					Console.WriteLine("Response was not OK: " + response);
			}
			catch (WebException wex)
			{
				ConsoleColor prev = Console.ForegroundColor;

				Console.ForegroundColor = ConsoleColor.Red;
				Console.WriteLine(wex.Message);

				HttpWebResponse res = (HttpWebResponse)wex.Response;
				if (res != null)
				{
					string tmpPath = Path.GetTempFileName();
					using (Stream str = res.GetResponseStream())
					using (StreamReader reader = new StreamReader(str))
					using (StreamWriter writer = new StreamWriter(tmpPath))
						writer.Write(reader.ReadToEnd());

					Console.WriteLine(string.Format("Response saved at '{0}'", tmpPath));
				}

				Console.ForegroundColor = prev;
			}
			catch (Exception ex)
			{
				ConsoleColor prev = Console.ForegroundColor;

				Console.ForegroundColor = ConsoleColor.Red;
				Console.WriteLine(ex.Message);

				Console.ForegroundColor = prev;
			}
			finally
			{
#if DEBUG
				if (Debugger.IsAttached)
				{
					Console.WriteLine("Press any key to exit...");
					Console.ReadKey();

				}
#endif
			}
			
			Environment.Exit(0);
		}

		static void ShowUsage()
		{
			Assembly assembly = Assembly.GetExecutingAssembly();
			object[] assemblyAtt = assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
			object[] assemblyCop = assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
			string title = ((AssemblyTitleAttribute)assemblyAtt[0]).Title;
			string copyRight = ((AssemblyCopyrightAttribute)assemblyCop[0]).Copyright;
			string version = assembly.GetName().Version.ToString();

			Console.WriteLine(title);
			Console.WriteLine(string.Format("{0} v{1}",copyRight, version));
			Console.WriteLine("");
			Console.WriteLine("Usage: twit /c|status");
			Console.WriteLine("");
			Console.WriteLine("/c 	: clears user stored credentials");
			Console.WriteLine("status 	: status to update at twitter.com");
			Console.WriteLine("");
			
		}
	}
}
